use sea_orm::{ActiveModelTrait, EntityTrait, NotSet};
use sea_orm::ActiveValue::Set;

use common::ctx::get_db_by_key;
use common::error::MyError;
use entity::{letter, postal};
use entity::prelude::Postal;
use model::game_email::ItemType;

pub struct PostalManager {}

impl PostalManager {
    pub async fn remove_postal(id: i32) -> Result<bool, MyError> {
        let res = Postal::delete_by_id(id).exec(&*get_db_by_key("taiwan_cain_2nd")?).await?;
        Ok(res.rows_affected == 1)
    }
    pub async fn create_postal(letter: letter::Model, charac_no: i32, item_id: u32, item_type: u32, count: i32, gold: u32) -> Result<postal::Model, MyError> {
        let mut model = postal::ActiveModel {
            postal_id: NotSet,
            occ_time: Set(letter.reg_date),
            send_charac_no: Set(0),
            send_charac_name: Set("dnf-admin-rs".to_string()),
            receive_charac_no: Set(charac_no),
            item_id: Set(item_id),
            add_info: Set(0),
            endurance: Set(1),
            upgrade: Set(0),
            amplify_option: Set(0),
            amplify_value: Set("0".to_string()),
            gold: Set(gold),
            delete_flag: Set(0),
            avata_flag: Set(0),
            seal_flag: Set(0),
            creature_flag: Set(0),
            letter_id: Set(letter.letter_id),
            seperate_upgrade: Set(0),
        };
        match ItemType::from(item_type) {
            ItemType::Equipment(_, _) => {
                model.add_info = Set(1);
            }
            ItemType::Consumables(_, _) => {
                model.add_info = Set(count);
            }
            ItemType::Material(_, _) => {
                model.add_info = Set(count);
            }
            ItemType::MissionMaterials(_, _) => {
                model.add_info = Set(count);
            }
            ItemType::Pet(_, _) => {}
            ItemType::PetEquipment(_, _) => {
                model.add_info = Set(1);
            }
            ItemType::PetConsumables(_, _) => {
                model.add_info = Set(count);
            }
            ItemType::Fashion(_, _) => {
                //时装固定是773
                model.add_info = Set(773);
            }
            ItemType::ExpertJob(_, _) => {
                model.add_info = Set(count);
            }
            ItemType::Other(_, _) => {
                model.add_info = Set(count);
            }
        }
        Ok(model.insert(&*get_db_by_key("taiwan_cain_2nd")?)
            .await?)
    }
}